<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑用户' : '新增用户'"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="form.username"
          placeholder="请输入用户名"
          :disabled="isEdit"
        />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="form.email"
          placeholder="请输入邮箱地址"
          type="email"
        />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
        <div v-if="isEdit" class="form-tip">
          留空则不修改密码
        </div>
      </el-form-item>
      
      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="form.nickname"
          placeholder="请输入昵称"
        />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="form.phone"
          placeholder="请输入手机号"
        />
      </el-form-item>
      
      <el-form-item label="头像" prop="avatar">
        <el-input
          v-model="form.avatar"
          placeholder="请输入头像URL"
        />
        <div v-if="form.avatar" class="avatar-preview">
          <el-image
            :src="form.avatar"
            :preview-src-list="[form.avatar]"
            fit="cover"
            style="width: 60px; height: 60px; border-radius: 50%;"
          />
        </div>
      </el-form-item>
      
      <el-form-item label="角色" prop="role_ids">
        <el-select
          v-model="form.role_ids"
          multiple
          placeholder="请选择角色"
          style="width: 100%"
        >
          <el-option
            v-for="role in roleOptions"
            :key="role.id"
            :label="role.name"
            :value="role.id"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { createUser, updateUser } from './api'
import { getAllRoles } from '../role/api'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const formRef = ref()
const loading = ref(false)
const roleOptions = ref([])

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => props.formData && props.formData.id)

// 表单数据
const form = reactive({
  username: '',
  email: '',
  password: '',
  nickname: '',
  phone: '',
  avatar: '',
  role_ids: [],
  status: 1
})

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { 
      validator: (rule, value, callback) => {
        if (!isEdit.value && !value) {
          callback(new Error('请输入密码'))
        } else if (value && value.length < 6) {
          callback(new Error('密码长度不能少于6位'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  nickname: [
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^$|^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 重置表单
const resetForm = () => {
  Object.keys(form).forEach(key => {
    if (key === 'status') {
      form[key] = 1
    } else if (key === 'role_ids') {
      form[key] = []
    } else {
      form[key] = ''
    }
  })
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await getAllRoles()
    roleOptions.value = response.data || []
  } catch (error) {
    console.error('获取角色列表失败:', error)
    // 如果角色接口还没实现，使用模拟数据
    roleOptions.value = [
      { id: 1, name: '超级管理员' },
      { id: 2, name: '普通用户' }
    ]
  }
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      // 编辑模式，填充表单数据
      Object.keys(form).forEach(key => {
        if (key === 'role_ids') {
          // 处理角色数据
          form[key] = newData.roles ? newData.roles.map(role => role.id) : []
        } else if (key === 'password') {
          // 编辑时密码为空
          form[key] = ''
        } else {
          form[key] = newData[key] || (key === 'status' ? 1 : '')
        }
      })
    } else {
      // 新增模式，重置表单
      resetForm()
    }
  },
  { immediate: true }
)

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const submitData = { ...form }
    
    // 如果是编辑模式且密码为空，则不提交密码字段
    if (isEdit.value && !submitData.password) {
      delete submitData.password
    }

    if (isEdit.value) {
      await updateUser(props.formData.id, submitData)
      ElMessage.success('更新用户成功')
    } else {
      await createUser(submitData)
      ElMessage.success('创建用户成功')
    }

    emit('success')
  } catch (error) {
    if (error !== false) {
      ElMessage.error(isEdit.value ? '更新用户失败' : '创建用户失败')
    }
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

// 初始化
onMounted(() => {
  fetchRoles()
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.avatar-preview {
  margin-top: 10px;
}
</style>
